import React, { useEffect, useRef } from 'react';
import { List, Typography, Avatar, Spin, Empty, Tooltip } from 'antd';
import { UserOutlined } from '@ant-design/icons';
import moment from 'moment';

const { Text } = Typography;

/**
 * 聊天消息列表组件
 * 显示历史聊天记录
 */
const ChatMessages = ({ 
  messages = [], 
  loading = false, 
  contactName = '' 
}) => {
  const messagesEndRef = useRef(null);

  // 新消息自动滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 格式化消息时间
  const formatTime = (timeStr) => {
    if (!timeStr) return '';
    
    // 如果是日期字符串（如"昨天 14:30"），直接返回
    if (typeof timeStr === 'string' && (timeStr.includes('昨天') || timeStr.includes('前天') || timeStr.includes('周'))) {
      return timeStr;
    }
    
    // 否则尝试格式化为相对时间
    try {
      const date = new Date(timeStr);
      return moment(date).calendar({
        sameDay: '[今天] HH:mm',
        lastDay: '[昨天] HH:mm',
        lastWeek: 'MM-DD HH:mm',
        sameElse: 'YYYY-MM-DD HH:mm'
      });
    } catch (error) {
      console.warn('时间格式化错误:', error);
      return timeStr;
    }
  };

  return (
    <div className="chat-messages-container">
      {/* 聊天标题 */}
      {contactName && (
        <div className="chat-messages-header">
          <Text strong>{contactName}</Text>
        </div>
      )}
      
      {/* 消息列表 */}
      {loading ? (
        <div className="chat-messages-loading">
          <Spin tip="加载消息中..." />
        </div>
      ) : messages.length === 0 ? (
        <Empty description="暂无聊天记录" />
      ) : (
        <List
          className="chat-messages-list"
          itemLayout="horizontal"
          dataSource={messages}
          renderItem={message => (
            <List.Item className={`chat-message-item ${message.is_self ? 'self' : 'other'}`}>
              {!message.is_self && (
                <Avatar 
                  className="chat-avatar" 
                  icon={<UserOutlined />} 
                  size="large" 
                />
              )}
              
              <div className={`message-bubble ${message.is_self ? 'self' : 'other'}`}>
                <div className="message-content">{message.content}</div>
                <Tooltip title={formatTime(message.time)}>
                  <div className="message-time">{formatTime(message.time)}</div>
                </Tooltip>
              </div>
              
              {message.is_self && (
                <Avatar 
                  className="chat-avatar" 
                  icon={<UserOutlined />} 
                  size="large" 
                />
              )}
            </List.Item>
          )}
        />
      )}
      
      {/* 用于自动滚动到底部的引用元素 */}
      <div ref={messagesEndRef} />
    </div>
  );
};

export default ChatMessages; 